<template>
	<view class="contain">
		<view class="title">
			{{text}}
		</view>
		<u-line></u-line>
		<view class="btn">
			<button type="primary" @click="show()" v-if="url">播放</button>
		</view>
	</view>
</template>

<script>
	export default {
		components: {

		},
		data() {

			return {
				text: "",
				type: false,
				url: "",
				audio: undefined
			}
		},
		methods: {
			show() {
				if (this.audio) {
					this.audio.destroy()
					this.audio = undefined
				}
				const innerAudioContext = uni.createInnerAudioContext();
				this.audio = innerAudioContext;
				innerAudioContext.autoplay = true;
				innerAudioContext.src = this.url;
				innerAudioContext.onPlay()
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				InnerAudioContext.destroy()
				this.audio = undefined
			}
		},
		onLoad(options) {
			this.text = options['text']
			this.type = options["type"]

			let that = this;
			if (this.type == "true") {
				console.log("普通话")
				const downloadTask = uni.downloadFile({
					url: `http://127.0.0.1:8000/api/generate_mandarin/?text=${this.text}`, //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('下载成功');
							console.log(res)
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								complete(res) {
									console.log(res)
									that.url = res.savedFilePath
								}
							});
						}
					}
				});
			} else {
				console.log("粤语")
				const downloadTask = uni.downloadFile({
					url: `http://127.0.0.1:8000/api/generate_cantonese/?text=${this.text}`, //仅为示例，并非真实的资源
					data: {
						"text": this.text
					},
					success: (res) => {
						if (res.statusCode === 200) {
							// console.log('下载成功');
							console.log(res.tempFilePath)
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								complete(res) {
									console.log(res)
									that.url = res.savedFilePath
								}
							});
						}
					},
					fail: (err) => {
						uni.showModal({
							content: "服务器异常",
							showCancel: false
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.contain {
		width: 100%;

		.title {
			margin: 20px;
			font-size: 30px;
		}

		.btn {
			margin: 20px;

		}

	}
</style>
